# -*- coding: utf-8 -*-
# Author: xiantingDeng
# Email: dengxianting@shxgroup.net
# Time: 2020/3/27 15:23

import yagmail

from common.util.read_util import OperationIni


def send_email(username, password, host, to_email, subject=None, contents=None, attachments=None,
               cc=None, bcc=None):
    '''
    发送邮件：支持抄送和附件方式
    :param username:发件人邮箱账号，如："123456@qq.com"
    :param password:发件人邮箱POP3/SMTP/IMAP客户端授权码，注意非发件人邮箱登录密码
    :param host:服务器地址邮箱服务器地址，如：POP3服务器: pop.163.com  SMTP服务器: smtp.163.com   IMAP服务器: imap.163.com
    :param to_email:收件人邮箱地址，如："123456@qq.com" ，多个时采用list方式传递，如：["123456@qq.com","234567@qq.com"]
    :param subject:邮件主题
    :param contents:邮件正文内容，可以直接以文本内容传递（包含html代码方式）
    :param 选填项，attachments:邮件附件内容，传递附件文件绝对路径，多个时采用list方式传递，如：["f1.txt", "f2.txt"]
    :param 选填项，cc:抄送收件人邮箱地址
    :param 选填项，bcc:暗抄送邮箱收件人地址，发件人处不显示该抄送地址，实际有发送信息
    :return:发送成功时返回True，失败时返回False
    '''
    email = yagmail.SMTP(user=username, password=password, host=host)
    try:
        email.send(to=to_email, subject=subject, contents=contents, attachments=attachments, cc=cc, bcc=bcc)
        return True
    except Exception as e:
        return False


def send_report_email(report_path=None):
    # 全局测试报告邮件发送
    config = OperationIni("email.ini").get_ini_file_path_section_data("config")
    result = send_email(username=config.get("username"), password=config.get("password"), host=config.get("host"),
                        to_email=config.get("to_email").split(","),
                        subject=config.get("subject"), contents=config.get("contents"), attachments=report_path)
    if (result):
        print("邮件发送成功")
    else:
        print("邮件发送失败！", result)
